﻿using Coldairarrow.Business.Base_Manage;
using Coldairarrow.Entity.View;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace Coldairarrow.Business.View
{
    public partial class View_Base_DepartmentBusiness : BaseBusiness<View_Base_Department>, IView_Base_DepartmentBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        readonly IOperatorDept _odept;
        public View_Base_DepartmentBusiness(IDbAccessor db, IOperator @operator, IOperatorDept @odept)
            : base(db)
        {
            _operator = @operator;
            _odept = @odept;
        }

        #region 外部接口

        //public async Task<PageResult<View_Base_Department>> GetDataListAsync(PageInput<ConditionDTO> input)
        //{
        //    var q = GetIQueryable();
        //    var where = LinqHelper.True<View_Base_Department>();
        //    var search = input.Search;

        //    //筛选
        //    if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
        //    {
        //        var newWhere = DynamicExpressionParser.ParseLambda<View_Base_Department, bool>(
        //            ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
        //        where = where.And(newWhere);
        //    }

        //    return await q.Where(where).GetPageResultAsync(input);
        //}

        public async Task<List<ViewBase_DepartmentTreeDTO>> GetTreeDataListAsync(ViewDepartmentsTreeInputDTO input)
        {
            var where = LinqHelper.True<View_Base_Department>();
            if (!input.parentId.IsNullOrEmpty())
                where = where.And(x => x.ParentId == input.parentId);
            var list = await GetIQueryable().Where(where).ToListAsync();

            var treeList = list
                .Select(x => new ViewBase_DepartmentTreeDTO
                {
                    Id = x.Id,
                    ParentId = x.ParentId,
                    Text = x.Name,
                    Value = x.Id,
                    TypeName = x.TypeName,
                }).ToList();

            return TreeHelper.BuildTree(treeList);
        }
        public async Task<List<Deptitemdto>> GetItemDeptid(ViewDepartmentsTreeInputDTO input)
        {
            //aa当前登录人部门id
            string deptid = _operator.Property.FactoryId;
            var ParentItem = await GetIQueryable().Where(x => x.Id == deptid).FirstOrDefaultAsync();
            List<Deptitemdto> ListData = new List<Deptitemdto>();
            Deptitemdto tree = new Deptitemdto();
            tree.Id = ParentItem.Id;
            tree.Name = ParentItem.Name;
            tree.parentId = ParentItem.ParentId;
            ListData.Add(tree);
            await GetDeptItemTree(ParentItem.Id, ListData);
            return ListData;
        }

        protected async Task<List<Deptitemdto>> GetDeptItemTree(string Id, List<Deptitemdto> ListData)
        {
            var ParentItem = await GetIQueryable().Where(x => x.ParentId == Id).ToListAsync();
            Deptitemdto tree = new Deptitemdto();
            foreach (var item in ParentItem)
            {
                if (item.Type == 3)
                {
                    Deptitemdto treedata = new Deptitemdto();
                    treedata.Id = item.Id;
                    treedata.Name = item.Name;
                    treedata.parentId = item.ParentId;
                    ListData.Add(treedata);
                }
                    await GetDeptItemTree(item.Id, ListData);
            }
            return ListData;
        }
      

        protected async Task<List<ViewBase_DepartmentTreeDTO>> GetItemTree(string ParentId, List<ViewBase_DepartmentTreeDTO> ListData, int index)
        {
            var ParentItem = await GetIQueryable().Where(x => x.Id == ParentId).OrderBy(m=>m.Sort).ToListAsync();
            ViewBase_DepartmentTreeDTO tree = new ViewBase_DepartmentTreeDTO();
            foreach (var item in ParentItem)
            {
                ViewBase_DepartmentTreeDTO treedata = new ViewBase_DepartmentTreeDTO();
                if (ListData.Where(x => x.Id == item.Id).Count() == 0)
                {
                    if (!item.ParentId.IsNullOrEmpty())
                    {
                        treedata.Id = item.Id;
                        treedata.ParentId = item.ParentId;
                        treedata.Text = item.Name;
                        treedata.Value = item.Id;
                        treedata.TypeName = item.TypeName;
                        ListData.Add(treedata);
                        await GetItemTree(item.ParentId, ListData, index);
                    }
                    else
                    {
                        if (index == 0)
                        {
                            treedata.Id = item.Id;
                            treedata.ParentId = item.ParentId;
                            treedata.Text = item.Name;
                            treedata.Value = item.Id;
                            treedata.TypeName = item.TypeName;
                            ListData.Add(treedata);
                        }
                        return ListData;
                    }
                }
            }
            return ListData;

        }
        /// <summary>
        /// 新增打印机获取隶属组织,
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<ViewBase_DepartmentTreeDTO>> GetTreeTypeDataListAsyncs(ViewDepartmentsTreeInputDTO input)
        {
            //获取登录人的部门信息
            var deptdata = await _odept.GetOperatorDeptType();
            var where = LinqHelper.True<View_Base_Department>();
            if (!input.parentId.IsNullOrEmpty())
                where = where.And(x => x.ParentId == input.parentId);
            if (deptdata.DeptType == 8)
            {
                where = where.And(x => x.Type == deptdata.DeptType && x.SupplierId == deptdata.SupplierId);
            }
            else
            {
                if (!input.Type.IsNullOrEmpty())
                {
                    where = where.And(x => x.Type == input.Type);
                }
            }

            
            //where = where.And(x => _operator.Property.DeptIds.Contains(x.Id));
            var list = await GetIQueryable().Where(where).OrderBy(m=>m.Sort).ToListAsync();
            List<ViewBase_DepartmentTreeDTO> ListData = new List<ViewBase_DepartmentTreeDTO>();

            int i = 0;
            foreach (var item in list)
            {
                if (ListData.Where(x => x.Id == item.Id).Count() == 0)
                {
                    ViewBase_DepartmentTreeDTO tree = new ViewBase_DepartmentTreeDTO();
                    tree.Id = item.Id;
                    tree.ParentId = item.ParentId;
                    tree.Text = item.Name;
                    tree.Value = item.Id;
                    tree.TypeName = item.TypeName;
                    ListData.Add(tree);
                }
                await GetItemTree(item.ParentId, ListData, i);
                i++;
            }

            return TreeHelper.BuildTree(ListData);
        }


        public async Task<View_Base_Department> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(View_Base_Department data)
        {
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(View_Base_Department data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }
        /// <summary>
        /// 根据上级法人 找下级车间
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<Deptitemdto>> GetItemDeptidvalueid(ViewDepartmentsTreeInputDTO input)
        {
            //var aa = _operator.Property.FactoryId;
            List<View_Base_Department> deptlist = await Db.GetIQueryable<View_Base_Department>().ToListAsync();
            var deptdata = deptlist.Where(x => x.Id == input.parentId).ToList();
            List<Deptitemdto> ListData = new List<Deptitemdto>();
            foreach (var item in deptdata)
            {
                if (item.Type == 3)
                {
                    Deptitemdto tree = new Deptitemdto();
                    tree.Id = item.Id;
                    tree.Name = item.Name;
                    tree.parentId = item.ParentId;
                    ListData.Add(tree);
                }
                GetFactoryItemTree(item.Id, ListData, deptlist);
            }
            //if (item != null)
            //{
            //    Deptitemdto tree = new Deptitemdto();
            //    tree.Id = item.Id;
            //    tree.Name = item.Name;
            //    tree.parentId = item.ParentId;
            //    ListData.Add(tree);
            //    await GetDeptItemTree(item.Id, ListData);
            //}
            return ListData;
        }

        protected List<Deptitemdto> GetFactoryItemTree(string Id, List<Deptitemdto> ListData, List<View_Base_Department> deptlist)
        {
            var ParentItem = deptlist.Where(x => x.ParentId == Id).ToList();
            Deptitemdto tree = new Deptitemdto();
            foreach (var item in ParentItem)
            {
                if (item.Type == 3)
                {
                    Deptitemdto treedata = new Deptitemdto();
                    treedata.Id = item.Id;
                    treedata.Name = item.Name;
                    treedata.parentId = item.ParentId;
                    ListData.Add(treedata);
                }
                GetFactoryItemTree(item.Id, ListData, deptlist);
            }
            return ListData;
        }



        /// <summary>
        /// 根据下属仓库/车间查找上级法人组织
        /// </summary>
        /// <param name="deptid"></param>
        /// <returns></returns>
        public async Task<View_Base_Department> GetDeptDataAsync(string deptid)
        {
            View_Base_Department detpdata = new View_Base_Department();
            detpdata = await Db.GetIQueryable<View_Base_Department>().Where(x => x.Id == deptid).FirstOrDefaultAsync();
            if (detpdata == null)
            {
                throw new BusException("没找到！");
            }
            string parentid = "";
            if (detpdata.Type == 7)
            {
                return detpdata;
            }
            else
            {
                if (!detpdata.ParentId.IsNullOrEmpty())
                {
                    parentid = detpdata.ParentId;
                    detpdata = null;
                    do
                    {
                        detpdata = await Db.GetIQueryable<View_Base_Department>().Where(x => x.Id == parentid).FirstOrDefaultAsync();
                        if (detpdata==null) {
                            throw new BusException("没找到！");
                        }
                      else if(detpdata != null)
                        {
                            parentid = detpdata.ParentId;
                        }
                    } while (detpdata.Type != 7);
                    
                }
                return detpdata;
            }
        }
        /// <summary>
        /// 根据下属车间/车间查找上级工厂
        /// </summary>
        /// <param name="deptid"></param>
        /// <returns></returns>
        public async Task<View_Base_Department> GetDeptDataAsyncWorkShop(string deptid)
        {
            View_Base_Department detpdata = new View_Base_Department();
            detpdata = await Db.GetIQueryable<View_Base_Department>().Where(x => x.Id == deptid).FirstOrDefaultAsync();
            string parentid = "";
            if (detpdata.Type == 7)
            {
                return detpdata;
            }
            else
            {
                if (!detpdata.ParentId.IsNullOrEmpty())
                {
                    parentid = detpdata.ParentId;
                    detpdata = null;
                    do
                    {
                        detpdata = await Db.GetIQueryable<View_Base_Department>().Where(x => x.Id == parentid).FirstOrDefaultAsync();
                        if (detpdata != null)
                        {
                            parentid = detpdata.ParentId;
                        }
                    } while (detpdata.Type != 7);

                }
                return detpdata;
            }
        }
        public  async Task<List<ViewBase_DepartmentTreeDTO>> GetTreeTypeDataListBumen(ViewDepartmentsTreeInputDTO input)
        {
            var where = LinqHelper.True<View_Base_Department>();
            if (!input.parentId.IsNullOrEmpty())
                where = where.And(x =>x.Type==6);
            var list = await GetIQueryable().Where(where).ToListAsync();
            var treeList = list
                .Select(x => new ViewBase_DepartmentTreeDTO
                {
                    Id = x.Id,
                    ParentId = x.ParentId,
                    Text = x.Name,
                    Value = x.Id,
                    TypeName = x.TypeName
                }).ToList();
            return TreeHelper.BuildTree(treeList);
        }

        public  async Task<List<Deptitemdto>> GetItemDeptidWorkShop(ViewDepartmentsTreeInputDTO input)
        {
            var aa = _operator.Property.DepartmentId;
            var item = await GetIQueryable().Where(x => x.Id == aa).FirstOrDefaultAsync();
            List<Deptitemdto> ListData = new List<Deptitemdto>();
            Deptitemdto tree = new Deptitemdto();
            tree.Id = item.Id;
            tree.Name = item.Name;
            tree.parentId = item.ParentId;
            if (item.Type==3) {
                ListData.Add(tree);
            }
           
            await GetDeptItemTreesssss(item.Id, ListData);
            return ListData;
        }
        protected async Task<List<Deptitemdto>> GetDeptItemTreesssss(string Id, List<Deptitemdto> ListData)
        {
            var ParentItem = await GetIQueryable().Where(x => x.ParentId == Id).ToListAsync();
            Deptitemdto tree = new Deptitemdto();
            foreach (var item in ParentItem)
            {
                if (item.Type == 3)
                {
                    Deptitemdto treedata = new Deptitemdto();
                    treedata.Id = item.Id;
                    treedata.Name = item.Name;
                    treedata.parentId = item.ParentId;
                    ListData.Add(treedata);
                }
                await GetDeptItemTreesssss(item.Id, ListData);
            }
            return ListData;
        }

        /// <summary>
        /// 获取登录人工厂下的所有部门信息
        /// </summary>
        /// <returns></returns>
        public async Task<List<ViewBase_DepartmentTreeDTO>> GetDeptListAsync()
        {
            //aa当前登录人部门id
            string deptid = _operator.Property.FactoryId;
            var list = await GetIQueryable().Where(x => x.Id == deptid).FirstOrDefaultAsync();
            List<ViewBase_DepartmentTreeDTO> ListData = new List<ViewBase_DepartmentTreeDTO>();
            ViewBase_DepartmentTreeDTO tree = new ViewBase_DepartmentTreeDTO();
            tree.Id = list.Id;
            tree.ParentId = "";
            tree.Text = list.Name;
            tree.Value = list.Id;
            tree.TypeName = list.TypeName;
            ListData.Add(tree);
            await GetDeptTreeItem(list.Id, ListData);

            return TreeHelper.BuildTree(ListData);
        }

        protected async Task<List<ViewBase_DepartmentTreeDTO>> GetDeptTreeItem(string Id, List<ViewBase_DepartmentTreeDTO> ListData)
        {
            var ParentItem = await GetIQueryable().Where(x => x.ParentId == Id).OrderBy(m => m.Sort).ToListAsync();
            ViewBase_DepartmentTreeDTO tree = new ViewBase_DepartmentTreeDTO();
            foreach (var item in ParentItem)
            {
                ViewBase_DepartmentTreeDTO treedata = new ViewBase_DepartmentTreeDTO();
                treedata.Id = item.Id;
                treedata.ParentId = item.ParentId;
                treedata.Text = item.Name;
                treedata.Value = item.Id;
                treedata.TypeName = item.TypeName;
                ListData.Add(treedata);
                await GetDeptTreeItem(item.Id, ListData);
            }
            return ListData;
        }

        #endregion

        #region 私有成员

        #endregion
    }
}